<?php

namespace frontend\controllers;

use common\models\lp\User;
use Yii;
use yii\web\Controller;

/**
 * 小程序获取openid页面
 */
class IndexController extends Controller
{
    //小程序传递code 换取openID
    public function actionGetCode()
    {
        $code = Yii::$app->request->get('code');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".getenv('XCX_APP_ID')."&secret=".getenv('XCX_APP_SECRET')."&js_code=".$code."&grant_type=authorization_code";
        $res = $this->api_request($url);
        file_put_contents('1.txt',json_encode($res));
        return json_encode($res);
    }


    //插入用户信息
    public function actionInsertUser(){
        $get = Yii::$app->request->get();
        $get['last_time'] = date("Y;m:d H:m:s",time());
        if(isset($get['openid']) && !empty($get['openid'])){
            $user = User::find()->where("openid= '".$get['openid']."'")->one();
            if($user){
                if(User::updateAll($get,"openid= '".$get['openid']."'")){
                    $msg = "更新成功";
                }else{
                    $msg = "更新失败";
                }
                $status = 1;
            }else{
                if(User::add($get)){
                    $msg = "添加成功";
                    $status = 1;
                }else{
                    $msg = "添加失败";
                    $status = 2;
                }
            }
        }else{
            $msg = "缺少openid";
            $status = 2;
        }
//        file_put_contents("./1.txt",$str);
        return json_encode([
            'status'=>$status,
            'msg'=>$msg,
            'data'=>"成功",
        ]);
    }
    //插入用户信息
    public function actionGetUser(){
        $get = Yii::$app->request->get();
        $post = Yii::$app->request->post();
        $str = json_encode($get)."ce".json_encode($post);
        file_put_contents("./1.txt",$str);
        return json_encode([
            'status'=>1,
            'code'=>1,
            'data'=>"ss",
        ]);
    }

    /*
    * 微信API调用方法
    * */
    public function api_request($url, $data = null)
    {
        //初始化cURL方法
        $ch = curl_init();
        //设置cURL参数（基本参数）
        $opts = array(
            //在局域网内访问https站点时需要设置以下两项，关闭ssl验证！
            //此两项正式上线时需要更改（不检查和验证认证）
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_TIMEOUT => 500,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_URL => $url,
        );
        curl_setopt_array($ch, $opts);
        //post请求参数
        if (!empty($data)) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        //执行cURL操作
        $output = curl_exec($ch);
        if (curl_errno($ch)) {    //cURL操作发生错误处理。
            var_dump(curl_error($ch));
            die;
        }
        //关闭cURL
        curl_close($ch);
        $res = json_decode($output);
        return ($res);   //返回json数据
    }
}